package org.hzero.data.permission.plugins;

import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.session.Configuration;

/**
 * 用于生成权限sql的会话
 *
 * @author tianhao.luo@hand-china.com
 */
public class SimpleSqlSource implements SqlSource {

    /**
     * 包含了权限的sql
     */
    private String permissionSql;
    /**
     * jdbc会话配置
     */
    private Configuration configuration;

    /**
     * 原始绑定sql
     */
    private BoundSql oldBoundSql;

    public SimpleSqlSource(String permissionSql, Configuration configuration,BoundSql boundSql) {
        this.permissionSql = permissionSql;
        this.configuration = configuration;
        this.oldBoundSql = boundSql;
    }

    @Override
    public BoundSql getBoundSql(Object parameterObject) {
        try {
            // 补充原始查询的查询条件additionalParameters给新的boundSql
            BoundSql boundSql = new BoundSql(configuration, permissionSql, oldBoundSql.getParameterMappings(), parameterObject);
            FieldUtils.writeDeclaredField(boundSql,"additionalParameters",FieldUtils.readDeclaredField(oldBoundSql,"additionalParameters",true),true);
            FieldUtils.writeDeclaredField(boundSql,"metaParameters",FieldUtils.readDeclaredField(oldBoundSql,"metaParameters",true),true);
            return boundSql;
        } catch (Exception e) {
            throw new RuntimeException("构造BoundSql失败"+e.getMessage());
        }
    }
}
